﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using DoxygenBrowser.Common.Model;
using DoxygenBrowser.Common.Parser;
using System.IO;
using DoxygenBrowserAddin.Data;

namespace DoxygenBrowserAddin.Controller
{
    public class TokenDictionaryLoader
    {
        public event ProgressChangedEventHandler ProgressChangedEvent;

        private TokenDictionary _tokenDictionary;
        public TokenDictionary TokenDictionary
        {
            get
            {
                return _tokenDictionary;
            }
        }

        private void WorkerThreadFunction()
        {
            // parse or load the token dictionary

        }

        public TokenDictionaryLoader()
        {
            _tokenDictionary = new TokenDictionary();
        }

        public bool IsLoading
        {
            get { return false; }
        }

        public void Process(Stream stream)
        {
            DocsetParser parser = new DocsetParser();
            parser.TokenAddedEvent += new EventHandler<TokenAddedEventArgs>(this.HandleTokenAdded);
            parser.ProgressChangedEvent += new ProgressChangedEventHandler(parser_ProgressChangedEvent);
            parser.Parse(stream);
            parser.ProgressChangedEvent -= parser_ProgressChangedEvent;
            OnCompletedWork();
        }

        void parser_ProgressChangedEvent(object sender, ProgressChangedEventArgs e)
        {
            if (ProgressChangedEvent != null)
            {
                ProgressChangedEvent(this, new ProgressChangedEventArgs(e.ProgressPercentage, null));
            }
        }

        public void Stop()
        {

        }

        public void HandleTokenAdded(object sender, TokenAddedEventArgs e)
        {
            string key = e.TokenIdentifier.FullName;
            key = normalizeIdentifier(key);

            _tokenDictionary.AddTokenEntry(key, e.FileLocation);
        }

        private string normalizeIdentifier(string key)
        {
            string normalizedKey = key;
            normalizedKey = normalizedKey.Replace("&lt;", "<");
            normalizedKey = normalizedKey.Replace("&gt;", "<");
            normalizedKey = normalizedKey.Replace(" ", "");
            return normalizedKey;
        }


        public void OnUpdateWorkStatus()
        {

        }

        public void OnCompletedWork()
        {

        }
    }
}
